import { ValidationPipe } from "@nestjs/common";
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
import { NestExpressApplication } from "@nestjs/platform-express";
import { join } from "path";
import { config } from "./config";
import { JwtService } from "@nestjs/jwt";
import { AllExceptions } from "./handler/all.exceptions";
import { DocumentBuilder, SwaggerModule } from "@nestjs/swagger";

// 图片访问拦截器
const fileFilter = (req: any, res: any, next: any) => {
  // try {
  //   // 验证token
  //   if (req.query.token) {
  //     // 从JwtService验证token
  //     const jwtService = new JwtService({ secret: config.jwt.secret });
  //     let payload = jwtService.verify(req.query.token);
  //     console.log(payload);
  //     //我们在这里将有效载荷分配给请求对象，以便我们可以在路由处理程序中访问它
  //     req["user"] = payload;
  //   }
  // } catch {
  //   res.send(JSON.stringify({ code: 401, message: "token无效" }));
  //   return;
  // }
  next();
};

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);
  app.useGlobalPipes(new ValidationPipe());
  app.enableCors();
  app.use(fileFilter);
  app.useStaticAssets(join(__dirname, "..", "public"),
    {
      // 不需要首页index.html
      index: false,
      // 不需要将目录重定向
      redirect: false
      // 虚拟前缀，访问资源都需要带上/public/
      // prefix: '/public/',
    }
  );
  app.useStaticAssets(join(__dirname, "uploadDefault"), {
    prefix: "/uploadDefault"
  });

  app.enable('trust proxy')

  // swagger
  const options =
    new DocumentBuilder()
      .setTitle('SugarLess')
      .setDescription('SugarLess')
      .setVersion('1')
      .addBearerAuth()
      .build()
  const document = SwaggerModule.createDocument(app, options)
  SwaggerModule.setup('/api-docs', app, document)
  await app.listen(3000);
}

bootstrap();
